<?php

namespace app\api\controller;

use app\common\controller\Api;
use addons\epay\library\Service as EpayService;
use EasyWeChat\Foundation\Application as WXPAY_APP;
use EasyWeChat\Payment\Order as WXPAY_ORDER;
use addons\third\model\Third;
use think\Db;
use app\admin\model\My_vegetables; 
use app\admin\model\My_props;
use app\admin\model\My_plant;
use app\admin\model\Granary;
use app\admin\model\User;
use think\Config;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        // $this->user_id = 2;
        $this->model = new \app\common\model\Order;
    }  

     /**
     * 商城商品列表(vegetables是蔬菜列表,props是肥料列表,land是土地我后台设定只有一个的)
     */
    public function shop(){

      $vegetables = Db::name('vegetables')->order('weigh desc')->select();
      $props = Db::name('props')->where('id','neq',6)->order('weigh desc')->select();
      $land = Db::name('props')->where('id','eq',6)->find();
      $return['vegetables'] = $vegetables;
      $return['props'] = $props;
      $return['land'] = $land;
      $this->success('商城商品列表',$return);
    }

    /**
     * 领养小树苗列表
     * @ApiSummary  (如果不传道具id过来就是浇水。   使用道具可以不传蔬菜id和位置过来，因为道具是独立加金币的。   小树苗id和首页蔬菜种子id传其中一个过来)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/order/tree)
    
     * @ApiReturn({
        {
  "code": 1,
  "msg": "领养小树苗列表",
  "time": "1594526669",
  "data": [
    {
      "id": 2,
      "name": "测试",
      "image": "http://nongchang.com/uploads/20200712/e012bdeca40527538eae90690b6cffb4.jpg",
      "fruit_name": "测试",
      "fruit_image": "http://nongchang.com/uploads/20200712/e012bdeca40527538eae90690b6cffb4.jpg",
      "fruit_num": "10",
      "fruit_limit": "10",
      "fruit_text": "10",
      "fruit_gold": "10.00",
      "gold": "10.00",
      "money": "10.00",
      "first_num": "10",
      "first_fee": "10.00",
      "renewal": "10",
      "renewal_fee": "10.00",
      "experience": "10.00",
      "status": "normal",
      "weigh": 2,
      "updatetime": 1594523270,
      "water_experience": "10.00",
      "can": 0,//1的时候表示金币足够可以领养
      "percentage": 20,//百分比
      "if_get": 0,//是否领养过。1：已经领养了。0待领养
      "remaining": 8//不足多少金币
    }
  ]
}
     })
     */

    public function tree(){
      $return = Db::name('plant')->where('status','normal')->order('weigh desc')->select();
      $self_gold = Db::name('user')->where('id',$this->user_id)->value('gold');
      $self_plant = Db::name('my_plant')->where('user_id',$this->user_id)->column('plant_id');

      foreach ($return as $key => $value) {

        if(in_array($value['id'], $self_plant)){
          $return[$key]['if_get'] = 1;
        }else{
          $return[$key]['if_get'] = 0;
        }
        if($self_gold>$value['gold']){
          $return[$key]['percentage'] = 100;
          $return[$key]['can'] = 1;
        }else{
          $return[$key]['percentage'] = $self_gold/$value['gold']*100;
          $return[$key]['can'] = 0;
          $return[$key]['remaining'] = (int)$value['gold']-(int)$self_gold;
        }
      }
      $this->success('领养小树苗列表',$return);
    }

    /**
     * 购买肥料或者驱虫剂，小树苗,首页蔬菜种子以及土地
     * @ApiSummary  (购买土地时候可以不用传商品id过来，因为土地只有一块)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/order/buy_props)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams  (name=good_id, type=int, required=true, description="商品id。就是id")
     * @ApiParams   (name="pay_type",type=int,required=false,description="支付类型:10=金币支付,20=微信支付")
     * @ApiParams   (name="spec_type",type=int,required=true,description="商品类型:10=首页蔬菜种子,20=肥料或者驱虫剂,30=小树苗,40=土地")
     */
    public function buy_props()
    {
        $params = input();
        $params['user_id'] = $this->user_id;
        $spec_type = input('spec_type');
        if(empty($spec_type))$this->error('请上传商品类型:spec_type');

        $good_id = $params['good_id'];
        
        $params['good_id'] = $good_id;

        switch ($spec_type) {
          // 40=土地
          case '40':

            $plant = Db::name('props')->where('id',6)->find(); 
            $params['image'] = $plant['image'];
            $params['name'] = $plant['name'];
            $params['gold'] = $plant['gold'];
            $params['total_price'] = $plant['money'];

            break;
            // 10=首页蔬菜种子
          case '10':

            $vegetables_data = Db::name('vegetables')->field('image,name,gold,money,id as vegetables_id,water_gold,text,name')->where('id',$good_id)->find();
            if(empty($vegetables_data))$this->error('数据找不到');

            $params['image'] = $vegetables_data['image'];
            $params['name'] = $vegetables_data['name'];
            $params['gold'] = $vegetables_data['gold'];
            $params['total_price'] = $vegetables_data['money'];

            $vegetables_data['user_id'] = $this->user_id;
            
            break;
          
          // 20=肥料或者驱虫剂
          case '20':
            $props_data = Db::name('props')->where('id',$good_id)->field('gold,money,image,name,text,add_gold,add_experience,id as props_id,status')->find();

            $params['image'] = $props_data['image'];
            $params['name'] = $props_data['name'];
            $params['gold'] = $props_data['gold'];
            $params['total_price'] = $props_data['money'];

            $props_data['user_id'] = $this->user_id;

            break;

          default:
            //小树苗
            $plant_num = Db::name('order')->where(['spec_type'=>'40','pay_status'=>'20','user_id'=>$this->user_id])->count();  
            if($plant_num==0)$this->error('请先购买土地再来领养小树苗');

            $now_self_plant = Db::name('my_plant')->where('user_id',$this->user_id)->count();
            if($now_self_plant>=$plant_num)$this->error('土地数量不足请再购买土地');

            $if_exist_plant = Db::name('my_plant')->where(['user_id'=>$this->user_id,'plant_id'=>$good_id])->find();
            if($if_exist_plant)$this->error('你已经购买过该树苗了');

            $plant_data = Db::name('plant')->where('id',$good_id)->field('gold,money,image,name,fruit_name,id as plant_id,experience as remaining_experience,water_experience,experience')->find();
            $plant_data['user_id'] = $this->user_id;

            $params['image'] = $plant_data['image'];
            $params['name'] = $plant_data['name'];
            $params['gold'] = $plant_data['gold'];
            $params['total_price'] = $plant_data['money'];

            break;
        }
         // 金币支付
        if($params['pay_type']=='10'){
          $User = new User();
          $self_gold = $User->where('id',$this->user_id)->find();
          if($self_gold['gold']<$params['total_price'])$this->error('金币余额不足');

          switch ($spec_type) {
             // 10=首页蔬菜种子
            case '10':
              $My_vegetables = new My_vegetables();
              $My_vegetables_data = $My_vegetables->where(['user_id'=>$this->user_id,'vegetables_id'=>(int)$good_id])->find();
              
              if($My_vegetables_data){
                $My_vegetables_data->setInc('num',1);
              }else{
                $insert_vegetables = $My_vegetables->allowField(true)->save($vegetables_data);
              }

              break;

            case '20':
                $My_props = new My_props();
                $my_props_data = $My_props->where(['user_id'=>$this->user_id,'props_id'=>(int)$good_id])->find();
                if($my_props_data){
                  $my_props_data->setInc('num',1);
                }else{
                  $My_props->allowField(true)->save($props_data);
                }
                break;

                // 购买小树苗
            case '30':
              $My_plant = new My_plant();
              $My_plant->allowField(true)->save($plant_data);
              break;

            // 土地
            case '40':
              Db::name('user')->where('id',$this->user_id)->setInc('land_num');
              break;
          }

          $self_gold->setDec('gold',$params['total_price']);
           // 创建订单数据
          $order_no = $this->model->order_add($params);
       
        }else{

          $order_no = $this->model->order_add($params);

          // 发起微信支付
          $this->init_wx_pay_for_wxapp();
       
          $third = Third::where(['user_id' => $this->user_id, 'platform' => 'wxapp'])->find();
      
          $payment = $this->wxapp->payment;
          // halt($payment);
          $attributes = [
              'trade_type'       => 'JSAPI',
              'body'             => '农场',
              'detail'           => '农场',
              'out_trade_no'     => $order_no,
              'openid'           => $third['openid'],
              'total_fee'        => $params['total_price']*100,
              'notify_url'       => Config::get('site.cdnurl').'/api/order/callback_for_wxapp',
          ];

          $order_detail = new WXPAY_ORDER($attributes);
          $result = $payment->prepare($order_detail);
          if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
              $prepayId = $result->prepay_id;
              $config = $payment->configForJSSDKPayment($prepayId); // 返回数组
              return $this->success('订单创建成功,预支付成功',$config);
          }
          return $this->error('微信支付调用失败',$result);
        }
        $this->success('购买成功');        
    }

    private function init_wx_pay_for_wxapp(){
        $config = get_addon_config('epay');
        $options = [
            'debug'  => true,
            'log' => [
                'level' => 'debug',
                'file'  => LOG_PATH . '/tmp/easywechat.log',
            ],
            'app_id'   => $config['wechat']['miniapp_id'],// 小程序 APPID
            'secret'   => $config['wechat']['app_secret'],//小程序密钥
            'payment' => [
                'merchant_id'        =>  $config['wechat']['mch_id'],//小程序商户号
                'key'                =>  $config['wechat']['key'],//小程序支付密钥
                'notify_url'         =>  \think\Request::instance()->domain().'/api/order/callback_for_wxapp',
            ],

        ];
        $this->wxapp = new WXPAY_APP($options);
    }

     /**
     * 小程序支付回调
     * @ApiSummary  (小程序支付回调)
     * @ApiRoute    (/api/index/callback_for_wxapp)
     */
    public function callback_for_wxapp(){
        $this->init_wx_pay_for_wxapp();
        $response = $this->wxapp->payment->handleNotify(function($notify, $successful){

            if ($successful) {
                $notify_json = json_encode($notify);
                if ($notify['return_code'] === 'SUCCESS') {
                    if($notify["result_code"] === "SUCCESS"){

                        $order_data = Db::name('order')->where(['order_no'=>$notify->out_trade_no])->find();

                        if($order_data['spec_type']!=='50'){
                          Db::name('order')->where('order_no',$notify->out_trade_no)->where('pay_status',10)->update([
                              'pay_status' => '40',
                              'pay_time' => time(),
                          ]);
                        }else{
                          Db::name('order')->where('order_no',$notify->out_trade_no)->where('pay_status',10)->update([
                              'pay_status' => '20',
                              'pay_time' => time(),
                          ]);
                        }
                        
                        switch ($order_data['spec_type']) {
                           // 10=首页蔬菜种子
                          case '10':
                            $My_vegetables = new My_vegetables();
                            $My_vegetables_data = $My_vegetables->where(['user_id'=>$order_data['user_id'],'vegetables_id'=>(int)$order_data['good_id']])->find();
                            
                            if($My_vegetables_data){
                              $My_vegetables_data->setInc('num',1);
                            }else{
                              $insert_vegetables = $My_vegetables->allowField(true)->save($vegetables_data);
                            }

                            break;
                            //肥料或者驱虫剂
                          case '20':
                              $My_props = new My_props();
                              $my_props_data = $My_props->where(['user_id'=>$order_data['user_id'],'props_id'=>(int)$order_data['good_id']])->find();
                              
                              if($my_props_data){
                                $my_props_data->setInc('num',1);
                              }else{
                                $props_data = Db::name('props')->where('id',$order_data['good_id'])->field('image,name,text,add_gold,add_experience,id as props_id')->find();
                                $props_data['user_id'] = $this->user_id;

                                $My_props->allowField(true)->save($props_data);

                              }
                              break;

                            // 土地
                            case '40':
                                Db::name('user')->where('id',$order_data['user_id'])->setInc('land_num');
                                break;
                            // 果实兑换
                            case '50':
                              $Granary = new Granary();
                              $my_granary = $Granary->where(['user_id'=>$order_data['user_id'],'plant_id'=>$order_data['good_id']])->find();  
                              $my_granary->setDec('num',$order_data['num']);
                              break;
                          
                          // 购买小树苗
                          default:
                            $plant_data = Db::name('plant')->where('id',$order_data['good_id'])->field('gold,money,image,name,fruit_name,id as plant_id,experience as remaining_experience,water_experience,experience')->find();
                            $plant_data['user_id'] = $order_data['user_id'];
                            
                            Db::name('my_plant')->insert($plant_data);
                            break;
                        }


                    }
                }
            }

            return true; // 返回处理完成
            
            
        });
        $response->send();
    }

  

}
